<!DOCTYPE html>
            
<HTML>
<HEAD>
<meta name="booktitle" content="Developing Applications With Objective Caml" >
 <meta charset="ISO-8859-1"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<META name="GENERATOR" content="hevea 1.05-7 of 2000-02-24">
<META NAME="Author" CONTENT="Christian.Queinnec@lip6.fr">
<LINK rel=stylesheet type="text/css" href="videoc-ocda.css">
<script language="JavaScript" src="videoc.js"><!--
//--></script>
<TITLE>
 Main program in C
</TITLE>
</HEAD>
<BODY class="regularBody">
<A HREF="book-ora117.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A>
<A HREF="book-ora119.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
<HR>

<H2> Main program in C</H2>
Until now, the entry point of our programs was in Objective CAML; the program
could then call C functions. Nothing prevents us from writing the entry point
in C, and having the C code call Objective CAML functions when desired.
To do this, the program must define the usual C <TT>main</TT> function.
This function will then initialize the Objective CAML runtime system
by calling the function <TT>caml_main(char **)</TT>, which takes as an
argument the array of command-line arguments that corresponds to the
<TT>Sys.argv</TT> array in Objective CAML. Control is then passed to the
Objective CAML code using callbacks (see page <A HREF="book-ora116.html#sec-Cfermeture">??</A>).<BR>
<BR>
<A NAME="toc162"></A>
<H3> Linking Objective CAML code with C</H3>
The Objective CAML compiler can output C object files (with extension <TT>.o</TT>)
instead of Objective CAML object files (with extension <TT>.cmo</TT> or <TT>.cmx</TT>).
All we need to do is set the <TT>-output-obj</TT> compiler flag.
<PRE>
ocamlc -output-obj files.ml
ocamlopt -output-obj.cmxa files.ml
</PRE>From the Objective CAML source files, an object file with default name
<TT>camlprog.o</TT> is produced.<BR>
<BR>
The final executable is obtained by linking, using the C compiler,
and adding the library <TT>-lcamlrun</TT> if the Objective CAML code was
compiled to bytecode, or the library <TT>-lasmrun</TT> if it was compiled
to native code.
<PRE>
cc camlprog.o filesC.o -lcamlrun 
cc camlprog.o filesC.o -lasmrun
</PRE>Calling Objective CAML functions from the C program is performed as
described previously, via the <TT>callback</TT> functions. The only
difference is that the initialization of the Objective CAML runtime system
is performed via the function <TT>caml_startup</TT>
instead of <TT>caml_main</TT>. <BR>
<BR>
<BR>
<BR>

<BR>
<BR>
<HR>
<A HREF="book-ora117.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A>
<A HREF="book-ora119.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
</BODY>
</HTML>
